//Given a positive integer n, generate an n x n matrix filled with elements from
// 1 to n2 in spiral order. 
//
// 
// Example 1: 
//
// 
//Input: n = 3
//Output: [[1,2,3],[8,9,4],[7,6,5]]
// 
//
// Example 2: 
//
// 
//Input: n = 1
//Output: [[1]]
// 
//
// 
// Constraints: 
//
// 
// 1 <= n <= 20 
// 
// Related Topics 数组 
// 👍 421 👎 0

package leetcode.editor.cn;

import java.util.ArrayList;

 class P54SpiralMatrixIi {
    public static void main(String[] args) {
        Solution solution = new P54SpiralMatrixIi().new Solution();
    }
    //leetcode submit region begin(Prohibit modification and deletion)
class Solution {
        public int[][] generateMatrix(int n) {
            int[][] matrix = new int[n][n];
            ArrayList<Integer> res = new ArrayList<>();
            if (matrix == null || matrix.length == 0) {
                return matrix;
            }
            int colStart = 0, colEnd = matrix[0].length - 1;
            int rowStart = 0, rowEnd = matrix.length - 1;
            int start = 1;
            while (colStart <= colEnd && rowStart <= rowEnd) {
                //对外圈进行处理
                //第一行
                for (int j = colStart; j <= colEnd; j++) {
                    matrix[rowStart][j] = start++;
                }
                //最后一列
                for (int i = rowStart + 1; i <= rowEnd; i++) {
                    matrix[i][colEnd]= start++;
                }
                //最后一行
                for (int j = colEnd - 1; j >= colStart && rowEnd != rowStart; j--) {
                    matrix[rowEnd][j]= start++;
                }
                //第一列
                for (int i = rowEnd - 1; i >= rowStart + 1 && colStart != colEnd; i--) {
                    matrix[i][colStart]= start++;
                }
                colStart++;
                colEnd--;
                rowStart++;
                rowEnd--;
            }
            return matrix;
        }
}
//leetcode submit region end(Prohibit modification and deletion)

}